// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package main

import (
	"net/http"
	"time"

	"github.com/gorilla/mux"
	logprinter "github.com/kumose/kmopt/pkg/logger/printer"
	"github.com/kumose/kmopt/server/handler"
)

type traceResponseWriter struct {
	http.ResponseWriter
	statusCode int
}

func (w *traceResponseWriter) WriteHeader(code int) {
	w.statusCode = code
	w.ResponseWriter.WriteHeader(code)
}

func httpRequestMiddleware(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		logprinter.Infof("Request : %s - %s - %s", r.RemoteAddr, r.Method, r.URL)
		start := time.Now()
		tw := &traceResponseWriter{w, http.StatusOK}
		h.ServeHTTP(tw, r)
		logprinter.Infof("Response [%d] : %s - %s - %s (%.3f sec)",
			tw.statusCode, r.RemoteAddr, r.Method, r.URL, time.Since(start).Seconds())
	})
}

func (s *server) router() http.Handler {
	r := mux.NewRouter()

	r.Handle("/api/v1/tarball/{sid}", handler.UploadTarbal(s.sm))
	r.Handle("/api/v1/component/{sid}/{name}", handler.SignComponent(s.sm, s.mirror))
	r.Handle("/api/v1/rotate", handler.RotateRoot(s.mirror))
	r.PathPrefix("/").Handler(s.static("/", s.mirror.Source(), s.upstream))

	return httpRequestMiddleware(r)
}
